<template>
  <div class="layout-col">
    <div class="layout-col bss">
      <div class="ww100 flex-bc plr12 ptb8 bs4">
        <div class="flex-sc">
          <span class="f15 fw">设备管理</span>
        </div>
        <div class="flex-ec flex1 h30">
          <div class="rad4 ptb6 plr10 flex-cc cursor bgi3 white ml10" 
            v-if="state.content.find(v=>{return typeof(v.key) == 'object'}) && state.content.find(v=>{return typeof(v.key) == 'object'})['key'].hasOwnProperty('add')" 
            @click.stop="handleClick('add', state.addItem)">
            <i-ep-plus class="f12 fw" /><span class="f14 ml5">{{state.content.find(v=>{return typeof(v.key) == 'object'})['key'].add}}</span>
          </div>
        </div>
      </div>
      <div class="row bgi22">
        <div :style="{textAlign: v.align, paddingRight: v.name=='操作'?'10px': 'inherit'}" v-for="(v, i) in state.content" :key="i" v-show="v.show" :class="v.width">{{v.name}}</div>
      </div>
      <div class="flex1 overlay ww100 flex-col-ss">
        <el-tree 
        class="ww100" 
        ref="treeRef" 
        :data="state.tree"
        :node-key="state.key" 
        :current-node-key="defaultId"
        :props="defaultProps"
        highlight-current    
        accordion
        @node-click="handleNodeClick"
        empty-text="暂无数据">
          <template #default="{ node, data }">
            <span class="row">
              <div v-show="v.show" :class="v.width" :style="{textAlign: v.align}" v-for="(v, i) in state.content" :key="i">
                <span v-if="typeof(v.key) == 'object'" class="i21 cursor mlr5" 
                v-for="(vv, kk, ii) in v.key" :key="ii" 
                :class="kk=='add'?'none'
                :kk=='child'&&data['class']==0?'none'
                :kk=='action'&&data['class']!=0?'none'
                :kk=='alart'&&data['class']!=0?'none'
                :kk=='alarm'&&data['class']!=0?'none'
                :kk=='cfg'&&data['class']!=0?'none':''" 
                @click.stop="handleClick(kk, data)">{{vv}}</span>
                <span v-else-if="v.key=='*'">{{index+1}}</span>
                <span v-else-if="v.type == 'find'">{{find(v.value[0], [v.value[1], data[v.key]], v.value[2])}}</span>
                <span v-else-if="v.type == 'time'">{{data[v.key] == 0?'/':parseTime(data[v.key])}}</span>
                <span v-else-if="v.type == 'switch'">
                  <el-switch v-model="data[v.key]" :active-text="v.value[1].name" :inactive-text="v.value[0].name" :active-value="v.value[1].value" :inactive-value="v.value[0].value" inline-prompt @change="handleClick('switch', data)"></el-switch>
                </span>
                <span v-else-if="v.type == 'icon1'" class="flex-sc">
                  <img v-if="data.class==0" class="mr5" src="@/assets/images/ic6.png" />
                  <img v-if="data.class==1" class="mr5" src="@/assets/images/ic5.png" />
                  <img v-if="data.class==2" class="mr5" src="@/assets/images/ic7.png" />
                  <img v-if="data.class==3" class="mr5" src="@/assets/images/ic8.png" />
                  <div>{{data[v.key]}}</div>
                </span>
                <span v-else>{{isNull(data[v.key]) && v.key!=''? '/' : data[v.key]}}</span>
              </div>
            </span>
          </template>
        </el-tree>
      </div>
      <Add @init="init" :state="state" ref="exposeRef" />
      <Cfg @init="init" :state="state" ref="exposeCfg" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import Add from '@/components/Add'
  import Cfg from '@/components/Cfg'
	const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const state = reactive({
	  ...publicStore.$state,
    key: 'id',
    parent: 'parent_id',
    query: {"o": "o_sensor", "p": [publicStore.distributId], "i": 0},
    content: [
      { width: 'flex1', show: true, align: 'left',  key: 'name', name: '名称', type: 'icon1' },
      { width: 'w50x4', show: true, align: 'left',  key: 'id',  name: '设备ID' },
      { width: 'w50x4', show: true, align: 'left',  key: 'bayNum', name: '间隔', type: 'find', value: [[], 'bayNum', 'bayName'] },
      { width: 'w50x2', show: true, align: 'left',  key: 'class', name: '分类', type: 'find', value: [[], 'value', 'name'] },
      { width: 'w50x4', show: true, align: 'left',  key: 'type', name: '类型', type: 'find', value: [[], 'type', 'name'] },
      { width: 'w50x4', show: true, align: 'left',  key: 'instlPos', name: '安装位置' },
      { width: 'w50x6', show: true, align: 'right', key: {add: '新增顶级', child:'新增子级', alarm: '告警', cfg: '属性', action: '动作', edit:'编辑', del: '删除'},  name: '操作' },
    ],
    editField: {},
    editFrom: [
      { required: true,  editshow: true,  name: '上级', key: 'parent_id', type: ['tree', [], 'id', 'parent_id', '顶级'] },
      { required: false, editshow: 'disabled',  name: '设备ID', key: 'id',  type: ['input', 'number'] },
      { required: true,  editshow: true,  name: '分类', key: 'class', type: ['select', [], 'value', 'name'] },
      { required: true,  editshow: true,  name: '类型', key: 'type', type: ['select', [], 'type', 'name'], relation: ['comm_params'] },
      { required: false, editshow: true,  name: '间隔', key: 'bayNum', type: ['select', [], 'bayNum', 'bayName'] },
      { required: true,  editshow: true,  name: '名称', key: 'name',  type: ['input'] },
      { required: false, editshow: true, name: '描述', key: 'description',  type: ['input'] },
      { required: false, editshow: true, name: '安装位置', key: 'instlPos',  type: ['input'] },
      { required: false, editshow: true, name: '上级类型', key: 'parent_type',  type: ['input'] },
      { required: true,  editshow: true, name: '网关机ID', key: 'gateway_id',  type: ['input'] },
      { required: false, editshow: true, name: '通信参数', key: 'comm_params',  type: ['input'] },
      { required: false, editshow: true, name: '图谱计算间隔', key: 'computeIntvalSec',  type: ['input'] },
      { required: false, editshow: true, name: '采样存储间隔', key: 'storeIntvalSecs',  type: ['input'] },
      { required: false, editshow: true, name: '告警引发持续存储间隔', key: 'alarmTigrStoreSecs',  type: ['input'] },
      { required: false, editshow: true, name: 'IP',   key: 'localSvcIP',  type: ['input'], condit: ["class", "2"] },
      { required: false, editshow: true, name: '端口', key: 'localSvcPort', type: ['input'], condit: ["class", "2"] },
      // { required: false, editshow: true, name: '底噪', key: 'snr',  type: ['input'] },
      // { required: false, editshow: true, name: '缩放', key: 'scale', type: ['input'] },
    ],
    addItem: {},
    sensorType: [
      {value: '0', name: '传感'},
      {value: '1', name: '汇聚'},
      {value: '2', name: '前置'},
      {value: '3', name: '节点'},
    ],
    templateList: [],
    voltageList: [],
    bayList: [],
  })
  let exposeCfg = $ref()
  let exposeRef = $ref()
  let treeRef = $ref()
  let defaultProps = {
    children: 'children',
    label: 'name',
  }
  let defaultId = $ref()

  onMounted(async() => {
    let query2 = {"o":"o_sensor_template"}
    let query3 = {"o":"o_wf_voltage"}
    let query4 = {"o":"o_wf_bay", "p": [publicStore.distributId]}
    let params = {queryApi2: query2, queryApi3: query3, queryApi4: query4}
    let res = await publicStore.post(params)
    state.templateList = res.queryApi2
    state.voltageList = res.queryApi3
    state.bayList = res.queryApi4
    init()
  })

  const setInit = () => {
    state.content.forEach(v => {
      if(v.key == 'class') v.value[0] = state.sensorType
      if(v.key == 'bayNum') v.value[0] = state.bayList
      if(v.key == 'type') v.value[0] = state.templateList
      if(v.key == 'parent_id') v.value[0] = publicStore._public.list
    })
    state.editFrom.forEach(v => {
      if(v.key == 'class') v.type[1] = state.sensorType
      if(v.key == 'bayNum') v.type[1] = state.bayList
      if(v.key == 'type') v.type[1] = state.templateList
      if(v.key == 'parent_id') v.type[1] = publicStore._public.list
    })
    state.addItem = {parent_id: '0', stationNum: publicStore.distributId}
  }

  const init = async(key) => {
    state.params = {queryApi: state.query}
    let res = await publicStore.post(state.params)
    state.empty = proxy.isNull(res)? true : false
    state.list = proxy.isNull(res)? [] : res.sort((a, b) => b.orderno - a.orderno)
    publicStore._public.list = state.list
    setInit()
    setTree(key)
  }

  const setTree = async(key) => {
    state.tree = proxy.treeData(state.list, state.key, state.parent, 'children')
    let node1 = proxy.findNode(state.tree, (node) => { return !node.children })
    let node2 = proxy.findNode(state.tree, (node) => { return node[state.key] == key })
    let node = proxy.isNull(node2)? node1 : node2
    await nextTick()
    handleNodeClick(node)
  }

  const handleNodeClick = async(val) => {
    defaultId = val[state.key]
    treeRef.setCurrentKey(defaultId, true)
    publicStore.active = val
  }

  const handleClick = (remark, val) => {
    if(remark == 'add' || remark == 'edit'){
      exposeRef.onVisable(val)
    }
    if(remark == 'del'){
      exposeRef.del(val, state.query, state.key, state.tree)
    }
    if(remark == 'child'){
      let newval = proxy.varObj(state.parent, val[state.key])
      if(val.hasOwnProperty('stationNum')){
        newval.stationNum = val.stationNum
      }
      exposeRef.onVisable(newval)
    }
    if(remark == 'cfg'){
      exposeCfg.onVisable(val)
    }
    if(remark == 'alarm'){
      proxy.toPath('/alarm', {id: val.id})
    }
    if(remark == 'action'){
      proxy.toPath('/action', {id: val.id})
    }
  }
</script>
  
<style scoped lang="scss">

</style>
  